let noticeDao = require('../dao/noticeDao');
let userDao = require('../dao/userDao');
let busiConst = require('../const/busiConst');
let stringUtil = require('../util/stringUtil');
let dateUtil = require('../util/dateUtil');
let redis = require('../dao/redis');

let assert = require('assert');

const { BusiError, SysError } = require('../exception/exception');

let noticeService = module.exports;

/**
 * 用户公告查询
 * @param uid
 * @param page
 * @returns {Promise<Object>}
 */
noticeService.queryUserPage = async function (uid, page) {
    let cacheKey = "nt:record:" + uid + ":" + page;
    let cache = await redis.get(cacheKey);
    if (!cache){
        let res = await noticeDao.queryPage({
            uid: uid,
            page: page
        });

        cache = res;

        await redis.set(cacheKey, cache, 60);
    }

    return cache;
};

/**
 * 系统公告查询
 * @param
 *      cond.page
 *      cond.isTop
 *      cond.author
 * @returns {Promise<void>}
 */
noticeService.querySysPage = async function (cond) {
    let cacheKey = "nt:record:sys:" + cond.page;
    let cache = await redis.get(cacheKey);
    if (!cache){

        let res = await noticeDao.queryPage({
            uid: -1,
            page: cond.page,
            isTop: cond.isTop,
            author: cond.author
        });

        cache = res;

        await redis.set(cacheKey, cache, 60);
    }

    return cache;
};

/**
 * 发布公告
 * @param notice
 *      notice.title
 *      notice.author
 *      notice.authorName
 *      notice.content
 *      notice.category
 *      notice.isTop
 *      notice.toUid
 * @returns {Promise<*>}
 *      0 失败, 1成功
 */
noticeService.publish = async function (notice) {
    let lockKey = "nt:publish:" + notice.author;
    let isSucc = await redis.lock(lockKey, 1, 20);
    if (!isSucc){
        console.logw("publish limit:", lockKey);
        return 0;
    }

    let res = await noticeDao.save(notice);

    return res;
};

/**
 * 公告置顶
 * @param id
 * @returns {Promise<*>}
 */
noticeService.setTop = async function (id) {
    let lockKey = "nt:top:" + id;
    let isSucc = await redis.lock(lockKey, 1, 5);
    if (!isSucc){
        console.logw("set top limit:", lockKey, id);
        return 0;
    }

    let res = await noticeDao.setTop(id, 1);

    return res;
};

/**
 * 公告撤销置顶
 * @param id
 * @returns {Promise<*>}
 */
noticeService.disableTop = async function (id) {
    let lockKey = "nt:top:" + id;
    let isSucc = await redis.lock(lockKey, 1, 5);
    if (!isSucc){
        console.logw("set top limit:", lockKey, id);
        return 0;
    }

    let res = await noticeDao.setTop(id, 0);

    return res;
};